package com.cinemahorairerapido;

import java.io.IOException;
import java.util.List;

import org.json.JSONException;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.cinemahorairerapido.adapter.FindCinemaAdapter;
import com.cinemahorairerapido.bean.Cinema;
import com.cinemahorairerapido.controller.AllocineController;
import com.cinemahorairerapido.controller.FindCinemaProgramTask;

public class FindCinemaActivity extends ListActivity {

	private ProgressDialog progressDialogFindCinema;

	private ProgressDialog progressDialogFindProgram;

	private EditText findCinemaText;

	private TextView resultTextView;

	private TextView noresultfoundTextView;

	private List<Cinema> findCinemaResult;

	private final static int DIALOG_EMPTY_TEXT_ERROR = 0;

	private FindCinemaProgramTask taskFindProgram;

	private FindCinemaTask taskFindCinema;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.findcinema);

		// block rotation
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		resultTextView = (TextView) findViewById(R.id.results);
		resultTextView.setVisibility(View.INVISIBLE);

		noresultfoundTextView = (TextView) findViewById(R.id.noresultfound);
		noresultfoundTextView.setVisibility(View.INVISIBLE);
		noresultfoundTextView.setHeight(0);

		findCinemaText = (EditText) findViewById(R.id.findCinemaText);

		Button findCinemaButton = (Button) findViewById(R.id.buttonFind);

		findCinemaButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if (findCinemaText.getEditableText() != null && !findCinemaText.getEditableText().toString().equals("")) {

					noresultfoundTextView.setVisibility(View.INVISIBLE);
					noresultfoundTextView.setHeight(0);

					progressDialogFindCinema = ProgressDialog.show(FindCinemaActivity.this, "", getResources().getText(R.string.searching), true,
							true, new DialogInterface.OnCancelListener() {

								@Override
								public void onCancel(DialogInterface dialog) {
									if (taskFindCinema != null) {
										taskFindCinema.cancel(true);
									}
								}
							});

					taskFindCinema = new FindCinemaTask();
					taskFindCinema.execute(findCinemaText.getEditableText().toString());

				} else {
					showDialog(DIALOG_EMPTY_TEXT_ERROR);
				}

			}
		});

	}

	private class FindCinemaTask extends AsyncTask<String, Integer, Long> {

		@Override
		protected Long doInBackground(String... value) {

			try {

				findCinemaResult = AllocineController.findCinema(value[0]);

				return new Long(1);

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return new Long(0);
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			// setProgressPercent(progress[0]);
		}

		@Override
		protected void onPostExecute(Long result) {

			if (result == 1) {
				resultTextView.setVisibility(View.VISIBLE);

				if (findCinemaResult.isEmpty()) {
					noresultfoundTextView.setVisibility(View.VISIBLE);
					noresultfoundTextView.setHeight(30);
				} else {

					// fill the list adapter
					FindCinemaActivity.this.setListAdapter(new FindCinemaAdapter(findCinemaResult, FindCinemaActivity.this));
				}

				// hide keyboard
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(findCinemaText.getWindowToken(), 0);

			} else {
				// no connection problem
				showDialog(FindCinemaProgramTask.DIALOG_TIMEOUT);
			}

			// close progress dialog
			if (progressDialogFindCinema != null) {
				progressDialogFindCinema.cancel();
				progressDialogFindCinema = null;
			}

		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Cinema cinema = null;
		for (int i = 0; i < findCinemaResult.size() && cinema == null; i++) {
			if (findCinemaResult.get(i).getId() != null && findCinemaResult.get(i).getId() == (int) id) {
				cinema = findCinemaResult.get(i);
			}
		}

		// Find data before launching view
		progressDialogFindProgram = ProgressDialog.show(this, "", getResources().getText(R.string.getshowtime), true, true,
				new DialogInterface.OnCancelListener() {

					@Override
					public void onCancel(DialogInterface dialog) {
						if (taskFindProgram != null) {
							taskFindProgram.cancel(true);
						}
					}
				});

		taskFindProgram = new FindCinemaProgramTask(this, progressDialogFindProgram);
		taskFindProgram.execute(cinema);

	}

	public void finish(View v) {
		finish();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case DIALOG_EMPTY_TEXT_ERROR:
			final TextView message = new TextView(this);
			message.setPadding(10, 10, 10, 10);

			String s = "Indiquer un texte pour votre recherche";

			message.setText(s);
			message.setMovementMethod(LinkMovementMethod.getInstance());

			dialog = new AlertDialog.Builder(this).setTitle("Erreur")//
					.setCancelable(true)//
					.setIcon(android.R.drawable.ic_dialog_alert)//
					.setView(message).create();
			break;
		case FindCinemaProgramTask.DIALOG_PARSE_KO:
			dialog = FindCinemaProgramTask.createJasonParseErrorDialog(this);
			break;
		case FindCinemaProgramTask.DIALOG_TIMEOUT:
			dialog = FindCinemaProgramTask.createNoConnectionDialog(this);
			break;
		default:
			dialog = null;
		}
		return dialog;
	}

}